<template>
  <view class="container">
    <u-popup :show="show" @close="handelClose" :round="10" mode="center">
      <view class="detail-wrapper">
        <view class="close" @click="handelClose">
          <image src="/static/imgs/close.png" mode=""></image>
        </view>
        <scroll-view scroll-y="true" style="max-height: 80vh;width: 80vw;">
          <view class="detail-con">
            <view class="goods-tit">
              <image :src="detailForm?.mainImage" mode=""></image>
              <text> {{detailForm?.name}}</text>
            </view>

            <view class="section" v-if="specGroups">
              <view class="spec-group" v-for="(group, idx) in specGroups" :key="idx">
                <view class="spec-group-name">{{ group.name }}</view>
                <view class="spec-item-wrap">
                  <view class="spec-item" :class="{ active: group.selectedId === item.id }"
                    @click="selectSpecItem(group, item)" v-for="(item, i) in group.items" :key="i">
                    {{ item.value }}
                  </view>
                </view>
              </view>
            </view>
            <!-- 3. 属性选择区域 -->
            <view class="section" v-if="attrGroups">
              <view class="attr-group" v-for="(group, idx) in attrGroups" :key="idx">
                <view class="attr-group-name">{{ group.name }}</view>
                <view class="attr-item-wrap">
                  <view class="attr-item" :class="{ active: group.selectedId === item.definitionValueId }"
                    @click="selectAttrItem(group, item)" v-for="(item, i) in group.items" :key="i">
                    {{ item.value }}
                  </view>
                </view>
              </view>
            </view>
            <!-- 2. 小料选择区域 -->
            <view class="section" v-if="toppingList.length>0">
              <view class="section-title" v-if="maxToppingTypes">加料（最多加 {{maxToppingTypes}}种）</view>
              <view class="section-title" v-else>加料（多选，可重复）</view>
              <view class="topping-item-wrap">
                <view class="topping-item" v-for="(topping, idx) in toppingList" :key="idx"
                  :class="{ active: topping.count > 0 }">
                  <view class="topping-info">
                    <text class="topping-name">{{ topping.name }}</text>
                    <text class="topping-price">¥{{ topping.price }}</text>
                  </view>
                  <view class="counter">
                    <image src="@/static/imgs/reduce.png" mode="" class="counter-btn" @click="decrement(topping)"
                      :disabled="topping.count === 0" v-if="topping.count > 0"></image>

                    <text class="count" v-if="topping.count > 0">{{ topping.count }}</text>
                    <image src="@/static/imgs/add.png" mode="" class="counter-btn" @click="increment(topping)">
                    </image>
                  </view>
                </view>
              </view>
            </view>
            <!-- 4. 底部操作栏 -->
          </view>
        </scroll-view>
        <view class="bottom-bar">
          <view class="selected-number">
            <u-number-box :min="1" :max="999" v-model="quantity" @plus="() => handlePlus()" @minus="() => handleMinus()"
              :buttonWidth="20" :buttonSize="20" buttonRadius="50%">
            </u-number-box>
          </view>
          <view class="total-info">
            <view class="total-price">
              合计：
              <text class="total-text">¥{{ totalPrice}}</text>
            </view>
            <button class="buy-btn" @click="handleAddCart">确定</button>
          </view>
        </view>
        <!--  <view class="btn-wrapper" v-if="detailForm?.stock>0">
            <button class="buy-btn" @click="handleBuyNow">立即购买</button>
            <button class="add-cart-btn" @click="handleAddCart">加入购物车</button>

          </view> -->
      </view>


    </u-popup>
  </view>
</template>

<script setup>
  import {
    ref,
    nextTick,
    computed,
    onMounted,
    watch,
    defineEmits
  } from 'vue'
  import {
    getBySpuId,
    addCartFun
  } from '@/requests/apis/takeOrder'
  const quantity = ref(1)
  const current = ref(0)
  const swipers = ref([])
  const emit = defineEmits(['closePopup', 'addCart'])
  const props = defineProps({
    productId: String,
    showPopup: Boolean,
    spuId: String,
    type: {
      type: String,
      default: 'goods',
    },
    phone:String
  })
  let show = ref(props.showPopup)
  let spuId = ref(props.spuId)
  let paddType = ref(props.type)
  let detailForm = ref()
  // 基础数据
  const showDebug = ref(false); // 调试开关
  const handelClose = () => {
    show.value = false;
    emit('closePopup')
  }
  // 增加数量
  const handlePlus = () => {
    const oldValue = Number(quantity.value)
    const newValue = oldValue + 1
    if (quantity.value > 8) {
      console.log('超限了')
    } else {
      quantity.value = newValue
    }
  }
  // 处理减号点击事件
  const handleMinus = () => {
    if (quantity.value <= 1) {
      console.log("删掉了")
    } else {
      quantity.value = Math.floor(quantity.value - 1)
    }
  }
  // 规格数据（笛卡尔积）
  let specData = ref([]);
  // 规格分组处理
  const specGroups = ref([]);

  // 小料数据
  const toppingList = ref([]);
  const maxToppingTypes = ref(); // 小料种类限制

  // 属性数据
  const attrGroups = ref([]);

  // 页面初始化时读取本地存储并设置选中状态
  onMounted(async () => {
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    let res = await getBySpuId({
      spuId: spuId.value
    })
    detailForm.value = res.Result
    swipers.value = res.Result.introImages.split(",")
    maxToppingTypes.value = res.Result.addonKind
    if (res.Result.skusList.length > 0) {
      specData.value = res.Result.skusList
      const a = res.Result.specs.map(group => {
        const items = group.specValues.map(item => ({
          id: item.specValueId,
          value: item.value,
          isAvailable: true
        }));

        return {
          name: group.name,
          selectedId: items[0]?.id || null,
          items: items
        };
      });
      specGroups.value = a
      console.log(specGroups.value, ' specGroups.value specGroups.value')
    }
    if (res.Result.attributeDtoList.length > 0) {
      // 第一步：过滤掉「整个属性分组」中 status 为 0 的项
      const validGroups = res.Result.attributeDtoList.filter(group => group.status !== 0);

      // 第二步：处理剩余有效分组的选项
      const processedGroups = validGroups.map(group => {
        const options = group.attributeValue || [];
        return {
          ...group,
          items: options,
          selectedId: options.length > 0 ? options[0].definitionValueId : null
        };
      });

      attrGroups.value = processedGroups;
    }
    if (res.Result.addonDtoList.length > 0) {
      // 先过滤掉 status 为 0 的小料
      toppingList.value = res.Result.addonDtoList
        .filter(topping => topping.status !== 0)
        .map(topping => ({
          ...topping,
          count: 0
        }));
    }
    uni.hideLoading()

  });
  // 计算属性
  const selectedToppingTypes = computed(() =>
    toppingList.value.filter(item => item.count > 0).length
  );

  const toppingTotalPrice = computed(() =>
    toppingList.value.reduce((sum, item) => sum + (item.price * item.count), 0)
  );

  // 计算商品总价（包含规格价 + 小料价）
  const totalPrice = computed(() => {
    // 基础价格转“分”（四舍五入，避免小数运算误差）
    const basePriceCent = Math.round((detailForm.value?.retailPrice || 0) * 100);
    let specPriceCent = basePriceCent; // 规格价默认复用基础价的“分”

    // 1. 判断规格数据是否为空
    const hasNoSpecData = specData.value.length === 0;
    // 2. 判断小料数据是否为空
    const hasNoToppingData = toppingList.value.length === 0;

    // 3. 核心逻辑：无规格且无小料时，直接返回“基础价 × 数量”
    if (hasNoSpecData && hasNoToppingData) {
      const quantityNum = Number(quantity.value) || 0; // 确保数量为有效数字
      const totalCent = basePriceCent * quantityNum; // 分单位计算总价
      return totalCent / 100; // 转回“元”单位
    }

    // 4. 有规格数据时，计算规格价（转“分”处理）
    if (!hasNoSpecData) {
      const matchedSku = specData.value.find(sku => {
        return sku.specValueDtoList.every(spec => {
          const group = specGroups.value.find(g => g.name === spec.name);
          if (!group) {
            console.warn(`未找到规格组：${spec.name}`);
            return false;
          }
          return group.selectedId === spec.specValueId;
        });
      });
      // 规格价转“分”（四舍五入，确保整数运算）
      specPriceCent = matchedSku ? Math.round(Number(matchedSku.retailPrice) * 100) : 0;
    }

    // 小料总价转“分”（四舍五入）
    const toppingTotalCent = Math.round(Number(toppingTotalPrice.value) * 100);
    // 数量转有效数字（避免非数字场景）
    const quantityNum = Number(quantity.value) || 0;

    // 计算总价：规格价×数量 + 小料价×数量（分单位累加）
    const totalCent = (specPriceCent * quantityNum) + (toppingTotalCent * quantityNum);
    return totalCent / 100; // 最终转回“元”单位
  });


  // 整理订单数据
  const cartData = computed(() => {
    // // 1. 处理规格（skuId）：无选中规格时传 null
    // const selectedSpecIds = specGroups.value.map(group => group.selectedId);
    // // 过滤可能的空值（如 group.selectedId 未选中时为 undefined/null），再判断是否为空
    // const validSkuId = selectedSpecIds.filter(id => id != null && id !== '').length > 0
    //   ? selectedSpecIds
    //   : null;
    // 1. 匹配当前选中的 SKU（核心逻辑）
    let matchedSku = null;
    if (specData.value.length > 0 && specGroups.value.length > 0) {
      matchedSku = specData.value.find(sku => {
        return sku.specValueDtoList.every(spec => {
          const group = specGroups.value.find(g => g.name === spec.name);
          if (!group) return false;
          return group.selectedId === spec.specValueId;
        });
      });
    }
    const skuId = matchedSku ? matchedSku.skuId : null;

    // 2. 处理属性（attrs）：无选中属性时传 null
    const selectedAttrIds = attrGroups.value.map(group => group.selectedId);
    const validAttrs = selectedAttrIds.filter(id => id != null && id !== '').length > 0 ?
      selectedAttrIds :
      null;

    // 3. 处理小料（addons）：无选中小料时传 null
    const filteredAddons = toppingList.value.filter(item => item.count > 0);
    const validAddons = filteredAddons.length > 0 ?
      filteredAddons.map(item => ({
        quantity: item.count,
        addonId: item.id
      })) :
      null;

    // 4. 组装最终数据（空字段传 null）
    return {
      quantity: quantity.value,
      spuId: spuId.value,
      skuId: skuId,
      attrs: validAttrs,
      addons: validAddons,
      productCombo: selectedInfo.value,
      phone: props.phone,
    };
  });

  // 拼接选中的规格、小料、属性信息
  const selectedInfo = computed(() => {
    let info = [];
    // 拼接规格信息
    const specInfo = specGroups.value
      .map(group => {
        const selectedItem = group.items.find(item => item.id === group.selectedId);
        return selectedItem ? selectedItem.value : "";
      })
      .filter(spec => spec)
      .join("，");
    if (specInfo) {
      info.push(specInfo);
    }

    // 拼接属性信息（温度、糖度等）
    const attrInfo = attrGroups.value
      .map(group => {
        const selectedItem = group.items.find(item => item.definitionValueId === group.selectedId);
        return selectedItem ? selectedItem.value : "";
      })
      .filter(attr => attr)
      .join("，");
    if (attrInfo) {
      info.push(attrInfo);
    }
    // 拼接小料信息
    const toppingInfo = toppingList.value
      .filter(item => item.count > 0)
      .map(item => `${item.name}*${item.count}`)
      .join("，");
    if (toppingInfo) {
      info.push(toppingInfo);
    }
    return info.join("，");
  });

  // 方法：规格选择
  const selectSpecItem = (group, item) => {
    group.selectedId = item.id;
    // // 校验1：当前规格组是否有可选项
    if (!group.items || group.items.length === 0) {
      uni.showModal({
        title: '提示',
        content: `此搭配暂不支持，请重新选择`,
        showCancel: false
      })
      return;
    }

    const oldSelectedId = group.selectedId; // 记录原选中ID，用于匹配失败时回退
    group.selectedId = item.id; // 临时选中新规格

    // 校验2：选中后是否能匹配到有效的商品SKU
    let matchedSku = null;
    if (specData.value.length > 0 && specGroups.value.length > 0) {
      matchedSku = specData.value.find(sku => {
        return sku.specValueDtoList.every(spec => {
          const targetGroup = specGroups.value.find(g => g.name === spec.name);
          return targetGroup?.selectedId === spec.specValueId;
        });
      });
    }

    // 若匹配不到有效SKU，回退选择并提示
    if (!matchedSku) {
      group.selectedId = oldSelectedId;
      uni.showModal({
        title: '提示',
        content: `此搭配暂不支持，请重新选择`,
        showCancel: false
      })
    }
  };

  // 方法：小料增减
  const increment = (topping) => {
    console.log("maxToppingTypes：", maxToppingTypes.value);

    // 如果topping.num为null，视为不限制份数，直接增加
    if (topping.num === null) {
      // 同时检查种类限制（如果有的话）
      if (maxToppingTypes.value !== null && maxToppingTypes.value !== undefined) {
        if (selectedToppingTypes.value < maxToppingTypes.value || topping.count > 0) {
          topping.count++;
        } else {
          uni.showToast({
            title: `最多选${maxToppingTypes.value}种小料`,
            icon: 'none'
          });
        }
      } else {
        // 既不限份数也不限种类，直接增加
        topping.count++;
      }
    }
    // topping.num有值时，检查是否超过最大份数
    else if (topping.count < topping.num) {
      if (maxToppingTypes.value !== null && maxToppingTypes.value !== undefined) {
        if (selectedToppingTypes.value < maxToppingTypes.value || topping.count > 0) {
          topping.count++;
        } else {
          uni.showToast({
            title: `最多选${maxToppingTypes.value}种小料`,
            icon: 'none'
          });
        }
      } else {
        topping.count++;
      }
    }
    // 超过最大份数限制
    else {
      uni.showToast({
        title: `最多选${topping.num}份`,
        icon: 'none'
      });
    }
  };

  const decrement = (topping) => {
    if (topping.count > 0) {
      topping.count--;
    }
  };

  // 方法：属性选择
  const selectAttrItem = (group, item) => {
    group.selectedId = item.definitionValueId;
  };

  // 方法：加入购物车
  const handleAddCart = async () => {
    console.log(cartData.value, 'cartData.valuecartData.value')
    uni.showLoading({
      title: '加载中...',
      mask: true
    })

    let res = await addCartFun(cartData.value)
    if (res.ResponseCode == 1) {
      show.value = false;
      setTimeout(() => {
        emit('addCart', quantity.value)
         uni.hideLoading()
      }, 1000)

    } else {
      uni.hideLoading()
    }
  };

  // 方法：立即购买
  const handleBuyNow = async () => {

  };
</script>

<style lang="scss">
  .detail-wrapper {
    background: linear-gradient(180deg, #E3F8FF 0%, #FFFFFF 100%);
    box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.04);
    border-radius: 10px;

    .close {
      box-sizing: border-box;
      text-align: right;
      padding: 14px;

      image {
        width: 14px;
        height: 14px;
      }
    }

    .detail-con {
      // margin-top: 33rpx;
      padding: 0 43px 31px;
      box-sizing: border-box;

      .goods-tit {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        image {
          width: 80px;
          height: 80px;
        }

        text {
          font-weight: 500;
          font-size: 14px;
          color: #333333;
          line-height: 20px;
          margin-left: 20px;
        }
      }

      .section {
        margin-bottom: 11px;

        .section-title {
          font-weight: 400;
          font-size: 12px;
          color: #666666;
          line-height: 22px;
          margin-bottom: 10rpx;
        }

        /* 规格选择 */
        .spec-group {
          margin-bottom: 11px;

          .spec-group-name {
            font-weight: 400;
            font-size: 12px;
            color: #666666;
            line-height: 22px;
            margin-bottom: 5px;
          }

          .spec-item-wrap {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
          }

          .spec-item {
            padding: 7px 18px;
            box-sizing: border-box;
            border-radius: 4px;
            border: 1rpx solid #D4D4D4;
            font-weight: 400;
            font-size: 12px;
            color: #333333;
          }

          .spec-item.active {
            background-color: rgba(15, 144, 253, 0.1);
            border: none;
            color: #0F90FD;
          }
        }

        // 属性选择区域

        .attr-group {
          margin-bottom: 11px;


          .attr-group-name {
            font-weight: 400;
            font-size: 12px;
            color: #666666;
            line-height: 22px;
            margin-bottom: 5px;
          }

          .attr-item-wrap {
            display: flex;
            flex-wrap: wrap;
            gap: 16px;
          }

          .attr-item {
            padding: 7px 18px;
            box-sizing: border-box;
            border-radius: 4px;
            border: 1rpx solid #D4D4D4;
            font-weight: 400;
            font-size: 12px;
            color: #333333;
          }

          .attr-item.active {
            background-color: rgba(15, 144, 253, 0.1);
            border: none;
            color: #0F90FD;
          }
        }


        /* 加料选择 */
        .topping-item-wrap {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          gap: 10px;
          width: 100%;

          .topping-item {
            border-radius: 4px;
            border: 1rpx solid #D4D4D4;
            font-weight: 400;
            font-size: 12px;
            color: #333333;
            display: flex;
            padding: 9px 12px;
            justify-content: space-between;
            box-sizing: border-box;
            margin-bottom: 10px;

            .topping-info {
              display: flex;
              white-space: nowrap;
              margin-right: 3px;

              .topping-price {
                margin-left: 3px;
              }
            }

            .counter {
              display: flex;
              align-items: center;

              .counter-btn {
                width: 15px;
                height: 15px;
              }

              .count {
                font-weight: 500;
                font-size: 14px;
                color: #0F90FD;
                margin: 0 10px;
              }
            }
          }

          .topping-item.active {
            background: rgba(15, 144, 253, 0.1);
            border: none;
            color: #0F90FD;
          }
        }
      }
    }

    .bottom-bar {
      padding: 26px 19px 26px 35px;
      box-sizing: border-box;
      background: #FFFFFF;
      box-shadow: 0px 2px 4px 0px rgba(27, 27, 27, 0.16);
      border-radius: 0px 0px 10px 10px;
      border-top: 1px solid #D8D8D8;
      backdrop-filter: blur(8.8235294117647px);
      display: flex;
      justify-content: space-between;

      .selected-number {
        :deep(.u-number-box__input) {
          height: 22px !important;
          background: #F3F3F3 !important;
          border-radius: 5px;
          line-height: 22px !important;
          min-height: 22px !important;
        }
      }



      .total-info {
        display: flex;
        align-items: center;

        .total-price {
          font-weight: 400;
          font-size: 14px;
          color: #333333;

          .total-text {
            font-weight: 500;
            font-size: 16px;
            color: #F32F1D;
          }
        }

        .buy-btn {
          flex: 1;
          font-weight: 500;
          font-size: 14px;
          color: #FFFFFF;
          margin-left: 24px;
          height: 36px;
          width:115px;
          line-height: 36px;
          background: #0F90FD;
          border-radius: 20px;

          &::after {
            border: none;
          }
        }
      }
    }

    .btn-wrapper {
      display: flex;
    }


  }
</style>
